package com.cardone.platform.authority.service;

import com.cardone.context.ContextHolder;
import com.cardone.platform.authority.dao.RolePermissionDao;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;

import java.util.List;
import java.util.Map;

/**
 * 角色与许可服务
 *
 * @author yaohaitao
 */
@Getter
@Setter
@org.springframework.transaction.annotation.Transactional(readOnly = true)
public class RolePermissionDefaultService extends com.cardone.common.service.SimpleDefaultService<com.cardone.platform.authority.dto.RolePermissionDto> implements RolePermissionService {
    @Override
    public Map<String, List<String>> findByUserId(String userId) {
        List<Map<String, Object>> mapList = this.getDao().findListByUserId(userId);

        Map<String, List<String>> listMap = Maps.newHashMap();

        if (CollectionUtils.isEmpty(mapList)) {
            return listMap;
        }

        List<String> roleCodes = Lists.newArrayList();

        List<String> permissionCodes = Lists.newArrayList();

        for (Map<String, Object> map : mapList) {
            String roleCode = MapUtils.getString(map, "ROLE_CODE");

            if (!roleCodes.contains(roleCode)) {
                roleCodes.add(roleCode);
            }

            String permissionCode = MapUtils.getString(map, "PERMISSION_CODE");

            if (!roleCodes.contains(roleCode)) {
                permissionCodes.add(permissionCode);
            }
        }

        listMap.put("roleCodes", roleCodes);
        listMap.put("permissionCodes", permissionCodes);


        return listMap;
    }

    @Override
    public RolePermissionDao getDao() {
        return ContextHolder.getBean(RolePermissionDao.class);
    }
}